<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryParams" :inline="true" v-if="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="goodsname">
        <el-input
          v-model="queryParams.goodsname"
          placeholder="请输入商品名称"
          clearable
          size="small"
          style="width: 240px"
          maxlength="80"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属类别" prop="classname">
        <el-input
          v-model="queryParams.classname"
          placeholder="请输入所属类别"
          clearable
          size="small"
          style="width: 240px"
          maxlength="80"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh-right" size="mini" @click="resetQuery('queryParams')">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <div class="top-right-btn">
        <el-tooltip class="item" effect="dark" content="刷新" placement="top">
          <el-button size="mini" circle icon="el-icon-refresh" @click="handleQuery" />
        </el-tooltip>
        <el-tooltip class="item" effect="dark" :content="showSearch ? '隐藏搜索' : '显示搜索'" placement="top">
          <el-button size="mini" circle icon="el-icon-search" @click="showSearch=!showSearch" />
        </el-tooltip>
      </div>
    </el-row>
    <el-table v-loading="loading" :data="tableDataList">
      <el-table-column label="商品ID" align="center" prop="goodsid" :show-overflow-tooltip="true" />
      <el-table-column label="商品编号" align="center" prop="goodsno" :show-overflow-tooltip="true" />
      <el-table-column label="所属类别" align="center" prop="classname" />
      <el-table-column label="商品名称" align="center" prop="goodsname" :show-overflow-tooltip="true"/>
      <el-table-column label="商品别名" align="center" prop="goodsname2" :show-overflow-tooltip="true"/>
      <el-table-column label="商品英文名" align="center" prop="engname" :show-overflow-tooltip="true"/>
      <el-table-column label="计量单位" align="center" prop="unit"/>
      <el-table-column label="零售价" align="center" prop="pricedetail"/>
      <el-table-column label="会员价" align="center" prop="pricemember"/>
      <el-table-column label="上架日期" align="center" prop="days" width="180px"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="220px">
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-upload2"
            @click="uploadSource(scope.row)"
            v-hasPerm="['upload_source']"
          >上传资源</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="downloadSource(scope.row)"
            v-hasPerm="['download_source']"
          >下载资源</el-button> -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="viewActivate(scope.row)"
            v-hasPerm="['view_activate']"
          >查看活动</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />

    <!-- 上传资源 -->
    <el-dialog title="上传资源" :visible.sync="uploadSourceDialog" width="50%" :close-on-click-modal="false">
      <div>
        <el-upload
          class="upload-demo"
          :action="action"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :headers="headers"
          multiple
          :file-list="fileList"
          :on-success="onSuccess">
          <el-button size="small" type="primary">点击上传资源</el-button>
          <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
        </el-upload>


      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-hasPerm="['upload_source']">确 定</el-button>
        <el-button @click="uploadSourceDialog = !uploadSourceDialog">取 消</el-button>
      </div>
    </el-dialog>

     <!-- 上传资源 -->
     <el-dialog title="查看活动" :visible.sync="viewActivateDialog" width="50%" :close-on-click-modal="false">
       <div>
         <el-row :gutter="10" class="mb8">
           <el-col :span="1.5">
             <el-button
               type="primary"
               icon="el-icon-plus"
               size="mini"
               @click="addActivityDialog = !addActivityDialog"
               v-hasPerm="['add_activity']"
             >新增活动</el-button>
           </el-col>
         </el-row>
          <el-table v-loading="activateLoading" :data="activateTableDataList">
            <el-table-column label="活动ID" align="center" prop="id" :show-overflow-tooltip="true" />
            <el-table-column label="活动名称" align="center" prop="activityName" :show-overflow-tooltip="true" />
            <el-table-column label="创建时间" align="center" prop="createTime" width="180px"/>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="220px">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-upload2"
                  @click="uploadSource(scope.row)"
                  v-hasPerm="['upload_source']"
                >上传资源</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-download"
                  @click="downloadSource(scope.row)"
                  v-hasPerm="['download_source']"
                >下载资源</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="activateTotal>0"
            :total="activateTotal"
            :page.sync="activateParams.current"
            :limit.sync="activateParams.size"
            @pagination="getActivateList"
          />
       </div>
       <div slot="footer" class="dialog-footer">
         <!-- <el-button type="primary" @click="submitForm" v-hasPerm="['upload_source']">确 定</el-button> -->
         <el-button @click="viewActivateDialog = !viewActivateDialog">关 闭</el-button>
       </div>


       <el-dialog
         width="30%"
         title="新增活动"
         :visible.sync="addActivityDialog"
         :append-to-body="true">
          <div>
            <el-form ref="activityForm" :model="activityForm" :rules="activityFormRules" label-width="80px">
              <el-form-item label="活动名称" prop="activityName">
                <el-input v-model="activityForm.activityName" size="mini"></el-input>
              </el-form-item>
            </el-form>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="addActivity" v-hasPerm="['add_activity']">确 定</el-button>
            <el-button @click="addActivityDialog = !addActivityDialog">取 消</el-button>
          </div>
       </el-dialog>
     </el-dialog>

  </div>
</template>

<script>
import { getProducrList, addProductSource,downloadGoodsSource,getProducrActivityList,addProductActivity } from "@/api/admin/productPackage";
import {getAccessToken} from '@/utils/auth'

export default {
    data() {
      return{
        queryParams: {
          goodsname: null,
          classname: null,
          current: 1, //当前页
          size: 10, //条数

        },                      //搜索条件
        showSearch: true,       //是否显示搜索框
        loading: false ,        //表格加载状态
        total: 0 ,              //总条数
        tableDataList: [],      //表格数据
        uploadSourceDialog: false , //上传资源
        goodsId: null,            //上传资源商品Id
        activityId: null,
        fileList:[],
        action: process.env.VUE_APP_BASE_API + "aliyunUpload/photoUpload",
        headers: {
          Authorization: "Bearer " + getAccessToken(),
        },
        viewActivateDialog: false, //查看活动

        activateLoading: false,  //请求状态
        activateTableDataList: [], //活动list
        activateTotal: 0 ,        //总条数
        activateParams:{
          current: 1, //当前页
          size: 10, //条数
          gid: this.goodsId
        },

        addActivityDialog: false,  //新增活动弹窗
        activityForm:{
          activityName: '',
          gid: this.goodsId
        },
        activityFormRules:{
          activityName: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
        }
      }
    },
    methods:{
      /**
       * 保存活动
       */
      addActivity(){
        this.$refs['activityForm'].validate((valid) => {
          if (valid) {
            this.activityForm.gid = this.goodsId;
            addProductActivity(this.activityForm).then(response => {
                this.activityForm.activityName = '';
                this.addActivityDialog  = false;
                this.activateParams.current = 1;
                this.getActivateList();
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      /**
       * 查看活动列表
       */
      viewActivate(row){
          this.viewActivateDialog = true;
          this.goodsId = row.id
          this.getActivateList();
      },
      /**
       * 获取活动列表
       */
      getActivateList(){
        this.activateLoading = true;
        this.activateParams.gid = this.goodsId;
        getProducrActivityList(this.activateParams).then(response => {
          this.activateTableDataList = response.data;
          this.activateTotal = response.total;
          this.activateLoading = false;
        })
      },
      /** 查询商品列表 */
      getList() {
        this.loading = true;
        getProducrList(this.queryParams).then(response => {
            this.tableDataList = response.data;
            this.total = response.total;
            this.loading = false;
          }
        );
      },
      //查询列表
      handleQuery(){
        this.queryParams.current = 1;
        this.getList();
      },
      //重置条件
      resetQuery(formName){
       if (this.$refs[formName] != undefined) {
         this.$refs[formName].resetFields();
         this.getList();
       }
      },
      //上传资源
      uploadSource(row){
        this.uploadSourceDialog = true;
        this.activityId = row.id
      },
      onSuccess(res){
        this.fileList.push(res.data)
      },
      //确认上传资源
      submitForm(){
          let requestParam = [];
          this.fileList.forEach(item=>{
            requestParam.push({
                                "gid": this.goodsId,
                                "activityId": this.activityId,
                                "sourceType": 2,
                                "sourceUrl": item.url,
                                "sourcePkUrl": item.relativelyUrl
                              })
          })
          addProductSource({"lhGoodsSourceList":requestParam}).then(res=>{
              //保存成功
              this.uploadSourceDialog = false;
              this.$message.success("保存成功")
              this.getList();
          })
      },
      //下载资源
      downloadSource(row){
        let that = this;
        this.$confirm("确定下载此商品资源?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          // const loading = this.$loading({
          //   lock: true,
          //   text: '努力下载中，请稍后...',
          //   spinner: 'el-icon-loading',
          //   background: 'rgba(0, 0, 0, 0.7)'
          // });
          // downloadGoodsSource({goodsId:row.id,sourceType: 1}).then(res=>{
          //   loading = false;
          //   this.$message.success("下载成功")
          // })
          window.location.href = process.env.VUE_APP_BASE_API + "/admin/productPackage/download?goodsId="+that.goodsId+"&activityId="+Number(row.id)+"&sourceType="+2;
        }).catch(() => {});
      },

      handleRemove(file, fileList) {
        console.log(file, fileList);
        this.fileList = fileList;
      },
      handlePreview(file) {
        console.log(file);
      }

    },
    mounted() {
      this.getList();
    }
}
</script>

<style scoped>
</style>
